package cloudoer.blog.service.impl;

import cloudoer.blog.base.BaseService;
import cloudoer.blog.entity.Article;
import cloudoer.blog.entity.Type;
import cloudoer.blog.service.ArticleService;
import cloudoer.blog.service.TypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("articleService")
public class ArticleServiceImpl extends BaseService implements ArticleService {

    public List<Article> getAll() {
        return articleMapper.selectAll();
    }

    public Article getById(String id) {
        Article a = articleMapper.selectByPrimaryKey(id);
        a.setBrowsecount((a.getBrowsecount()+1));
        articleMapper.updateByPrimaryKeySelective(a);
        return a;
    }

    public List<Article> getByType(String typeId){
        if (StringUtils.isBlank(typeId)){
            return articleMapper.selectCondition(new HashMap(), "postdate");
        }
        Map map = new HashMap();
        map.put("typeId",typeId);
        return articleMapper.selectCondition(map, "postdate");
    }

    /**
     * 按列排序后返回，最多只返回10条数据
     * @param orderBy
     * @return
     */
    public List<Article> getByOrder(String orderBy){
        List<Article> list = articleMapper.selectCondition(new HashMap(), orderBy);
        while (list.size() > 8){
            list.remove(8);
        }
        return list;
    }

    public void add(Article article) {
        articleMapper.insertSelective(article);
    }

    public void update(Article article) {
        articleMapper.updateByPrimaryKeySelective(article);
    }

    public void delete(String id, File imageFolder) {
        if (imageFolder != null && imageFolder.exists() && imageFolder.isDirectory()){
            deleteFile(imageFolder);
        }
        articleMapper.deleteByPrimaryKey(id);
    }

    public int endorse(String id) {
        Article a = articleMapper.selectByPrimaryKey(id);
        a.setEndorsecount((a.getEndorsecount()+1));
        articleMapper.updateByPrimaryKeySelective(a);
        return a.getEndorsecount();
    }

    private void deleteFile (File file){
        if (file != null && file.exists() && file.isDirectory()){
            for (String s : file.list()){
                deleteFile(new File(file.getParent() + File.separator +
                        file.getName() + File.separator + s));
            }
            file.delete();
        }else if (file != null && file.exists() && file.isFile()){
            file.delete();
        }
    }
}
